<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\h5;

use app\wework\controller\Base;
use app\wework\model\BaseModel;
use app\wework\model\user\reply\ReplyModel;
use app\wework\model\Helper;
use app\wework\model\QyWechatApi;
use app\wework\model\JsSdk;
use think\facade\Log;
use think\facade\Db;
use think\facade\View;
use app\wework\model\user\radar\InteractiveRadarModel;


/**
  * 快捷回复，雷达  h5端
 */
class InteractiveRadar extends Base
{
	public function index(){
		$code = $this->req->param("code");
		$wid = $this->req->param("wid");
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$wid = $config["wid"];
		if($code){
			$resArr = QyWechatApi::getuserinfo($wid,$code);
			$jsSdkServe = new JsSdk($config["corp_id"],$wid);
			$wxConfig = $jsSdkServe->getSignPackage();
			$agentConfig = $jsSdkServe->getSignPackage('','agent');
			$where["wid"] = $wid;
			$where["userid"] = $resArr["UserId"];
			$user = Helper::getUser($where);
			if(!$user)return error("请先同步通讯录成员");
			View::assign("corp_id", $config["corp_id"]);
			View::assign("agent_id", $selfapp["agent_id"]);
			View::assign("wxConfig", $wxConfig);
			View::assign("agentConfig", $agentConfig);
			View::assign("wid", $wid);
			View::assign("userId", $user["id"]);
			return view();
		}else{
			$redirect_uri = urlencode($this->req->domain().'/wework/h5.InteractiveRadar/index.html?wid='.$wid);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config["corp_id"].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			return redirect($url);
		}
	}

	/*
	* 快捷回复
	* page 页码
	* userId 员工id
	* external_userid 客户 external_userid
	* type 类型查询
	* group 分组查询
	* title 标题查询
	*/
	public function quick(){
		$grouping_id = $this->req->param("grouping_id");
		$title = $this->req->param("title");
		$external_userid = $this->req->param("external_userid");
		$userId = $this->req->param("userId");
		$wid = $this->req->param("wid");
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$where["wid"] = $wid;
		if($grouping_id)$where["grouping_id"] = $grouping_id;
		$grouping_list = Db::table("kt_wework_reply_group")->where(["wid"=>$wid])->select()->toArray();
		$reply_list = Db::table("kt_wework_reply_list")
		                ->where($where);
		if($title) $reply_list= $reply_list->where('title','like',"%{$title}%");
                  $reply_list= $reply_list->json(["welcome_data"])
		                ->select()
		                ->toArray();
		$jsSdkServe = new JsSdk($config["corp_id"],$wid);
		$wxConfig = $jsSdkServe->getSignPackage();
		$agentConfig = $jsSdkServe->getSignPackage('','agent');
		
		View::assign("corp_id", $config["corp_id"]);
		View::assign("agent_id", $selfapp["agent_id"]);
		View::assign("wxConfig", $wxConfig);
		View::assign("agentConfig", $agentConfig);
		View::assign("grouping_id", $grouping_id);
		View::assign("reply_list", $reply_list);
		View::assign("title", $title);
		View::assign("external_userid", $external_userid);
		View::assign("grouping_list", $grouping_list);
		View::assign("userId", $userId);
		View::assign("wid", $wid);
		return view();
	}


	/**
	* 快捷回复组装回复数组
	*/
	public function getReplyInfo(){
		$id = $this->req->param("id");
		$wid = $this->req->param("wid");
		$quick = Db::table("kt_wework_reply_list")->where(["id"=>$id])->json(["welcome_data"])->find();
		$data = [];
		foreach ($quick["welcome_data"] as $value){
		    if($value["type"] == 1){
    			$data[] = [
    				'type' => 1,
    				'text' => $value["text"]
    			];
    		}elseif($value["type"] == 2){
    			$mediaId = QyWechatApi::mediaUpload($wid,$value["image_url"],"image")["media_id"];
    			$data[] = [
    				'type' => 2,
    				'media_id' => $mediaId
    			];
    		}elseif($value["type"] == 3){
    		    $url = $this->req->domain();
    		    if(substr($value["video_url"],0,strlen($url)) == $url)$value["video_url"] = str_replace($this->req->domain(),".",$value["video_url"]);
    // 			$video_path =$this->analysisTengxunVideo($value["video_url"]);
    			$mediaId = QyWechatApi::mediaUpload($wid,$value["video_url"],'video')['media_id'];
    			$data[] = [
    				'type' => 3,
    				'media_id' => $mediaId
    			];
    		}elseif($value["type"] == 4){
    		    $url = $this->req->domain();
    		    if(substr($value["file_url"],0,strlen($url)) == $url)$value["file_url"] = str_replace($this->req->domain(),".",$value["file_url"]);
    			$mediaId = QyWechatApi::mediaUpload($wid,$value["file_url"],"file")["media_id"];
    			$data[] = [
    				'type' => 4,
    				'media_id' => $mediaId
    			];
    		}elseif($value["type"] == 5){
    			$data[] = [
    				'type' => 5,
    				'link_url' => $value["link_url"],
    				'link_title' => $value["link_title"],
    				'link_pic' => $value["link_image_url"],
    				'link_desc' => $value["link_desc"],
    			];
    		}elseif($value["type"] == 6){
    			$data[] = [
    				'type' => 6,
    				'title' => $value["miniprogram_title"],
    				'imgurl' => $value["miniprogram_imgurl"],
    				'appid' => $value["miniprogram_appid"],
    				'page' => $value["miniprogram_page"],
    			];
    		}
		}
		Db::table("kt_wework_reply_list")->where(["id"=>$id])->update(["size"=>$quick["size"]+1]);
		return success("获取成功",$data);
	}


	/**
	* 解析腾讯视频地址
	*/
	public function analysisTengxunVideo($videoUrl){
	  	//解析腾讯视频网址
		$vid=trim(strrchr($videoUrl, '/'),'/');
		$vid=substr($vid,0,-5);
		$json=file_get_contents("http://vv.video.qq.com/getinfo?vids=".$vid."&platform=101001&charge=0&otype=json");
		$json=substr($json,13);
		$json=substr($json,0,-1);
		$a=json_decode(html_entity_decode($json));
		$sz=json_decode(json_encode($a),true);
		$url=$sz['vl']['vi']['0']['ul']['ui']['3']['url'];
		$fn=$sz['vl']['vi']['0']['fn'];
		$fvkey=$sz['vl']['vi']['0']['fvkey'];
		$videos=$url.$fn.'?vkey='.$fvkey;
		//如果是自上传视频
		if($url == '')$videos=$videoUrl;
		return $videos;
	}

	public function radar(){
		$external_userid = $this->req->param("external_userid");
		$userId = $this->req->param("userId");
		$wid = $this->req->param("wid");
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$data = InteractiveRadarModel::radarList($wid);
// 		var_dump($data);die;
		$count = count($data);
		$jsSdkServe = new JsSdk($config["corp_id"],$wid);
		$wxConfig = $jsSdkServe->getSignPackage();
		$agentConfig = $jsSdkServe->getSignPackage('','agent');

		View::assign("agentConfig", $agentConfig);
		View::assign("wxConfig", $wxConfig);
		View::assign("count", $count);
		View::assign("corp_id", $config["corp_id"]);
		View::assign("agent_id", $selfapp["agent_id"]);
		View::assign("external_userid", $external_userid);
		View::assign("userId", $userId);
		View::assign("wid", $wid);
		View::assign("data", $data);
		return view();
	}

	public function getRadarInfo(){
		$id = $this->req->param("id");
		$wid = $this->req->param("wid");
		$user_id = $this->req->param("user_id");
	    $radar  = ReplyModel::find("kt_wework_radar",$id);
		$selfurl = $this->req->domain().'/wework/h5.InteractiveRadar/collectClcuserInfor.html?id='.$id.'&wid='.$wid.'&user_id='.$user_id;
		$data = [
			'link_url' => $selfurl,
			'link_title' => $radar["link_title"],
			'link_pic' => $radar["image_url"],
			'link_desc' => $radar["description"],
		];
		return success("获取成功",$data);
	}

	public function collectClcuserInfor(){
		$user_id = $this->req->param("user_id");
		$id = $this->req->param("id");
		$wid = $this->req->param("wid");
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		$code = $this->req->param("code");
		$radar  = ReplyModel::find("kt_wework_radar",$id);
		if(!$radar) die('链接不存在');
		$wid = $radar["wid"];
		if($code){
			$resArr = QyWechatApi::getuserinfo($wid,$code);
			if(isset($resArr['external_userid'])){
				$where = [];
				$where['wid'] = $wid;
				$where['staff_id'] = $user_id;
				$where['external_userid'] = $resArr['external_userid'];
				$externalcontac = Helper::getCustomer($where);
				if($externalcontac["id"]){
					$radar_record = ReplyModel::addRadar($wid,$resArr['external_userid'],$id);
					if($radar_record){
						// 发送提醒
						$qyuser = Helper::getUser(["id"=>$user_id]);
						if($radar["behavior_inform"] == 1 && $user_id){
							$content = $externalcontac["name"].'点击了标题是<'. $radar["link_title"].'>的雷达链接';
							$res = QyWechatApi::sendText($wid,$qyuser["userid"],$content);
						}
						//记录动态
						if($radar["dynamic_inform"] == 1){
							$dynamic = ReplyModel::add_Dynamic($wid,$resArr['external_userid'],5,$id,$user_id);
						}
						//打标签
						if($radar["ex_tag_inform"] == 1){
							$add_tag = json_decode($radar["ex_tag"],1)?:[];
							if($add_tag){
							    $param = [
								  'userid' => $qyuser['userid'],
								  'external_userid' => $resArr['external_userid'],
								  'add_tag' => $add_tag,
								  'remove_tag' => []
							  	];
							    $res = QyWechatApi::editMarkTag($param,$wid);
							    if($res['errcode'] == 0){
							    	$tags = json_decode($externalcontac["tags"],1)?:[];
							    	$data["tags_info"] = json_encode(array_unique(array_merge($add_tag,$tags)),320);
							    	$data["tags"] = json_encode(array_unique(array_merge($add_tag,$tags)),320);
							    	Helper::saveCustomer(["id"=>$externalcontac["id"]],$data);
							    }   
							}
						}
					}
				}	
			}
			//跳转
			return redirect($radar["link"]);
		}else{
			$redirect_url = urlencode($this->req->domain().'/wework/h5.InteractiveRadar/collectClcuserInfor.html?id='.$id.'&user_id='.$user_id.'&wid='.$wid);
			$auth_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config["corp_id"].'&redirect_uri='.$redirect_url.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			return redirect($auth_url);
		}
	}
	
	public function customer_infos(){
	    return view();
	}
}